package com.zee.wechat.framework.advice;

import com.zee.wechat.framework.enums.ResultCode;
import com.zee.wechat.framework.exception.ApiException;
import com.zee.wechat.framework.vo.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author Zee
 */
@RestControllerAdvice
@Slf4j
public class ControllerExceptionAdvice {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseResult methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        // 从异常对象中拿到ObjectError对象
        log.error(e.getMessage(),e);
        ObjectError objectError = e.getBindingResult().getAllErrors().get(0);
        return new ResponseResult(ResultCode.VALIDATE_ERROR, objectError.getDefaultMessage());
    }

    @ExceptionHandler(BindException.class)
    public ResponseResult bindExceptionHandler(BindException e) {
        // 从异常对象中拿到ObjectError对象
        log.error(e.getMessage(),e);
        ObjectError objectError = e.getBindingResult().getAllErrors().get(0);
        return new ResponseResult(ResultCode.VALIDATE_ERROR, objectError.getDefaultMessage());
    }

    @ExceptionHandler(ApiException.class)
    public ResponseResult apiExceptionHandler(ApiException e) {
        log.error(e.getMessage(), e);
        return new ResponseResult(e.getCode(), e.getMsg(), e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public ResponseResult handleException(Exception e) {
        log.error(e.getMessage(), e);
        return new ResponseResult(ResultCode.ERROR);
    }
}